import { NextRequest, NextResponse } from 'next/server'
import { semanticIndexingService } from '@/lib/services/semantic-indexing-service'
import { createServerSupabaseClient } from '@/lib/supabase'
export async function POST(
req: NextRequest,
{ params }: { params: { id: string } }
) {
try {
const bookId = params.id
const supabase = createServerSupabaseClient()
// Get current user session from auth header
const authHeader = req.headers.get('authorization')
let user
try {
if (authHeader) {
const { data: { user: authUser }, error: authError } = await supabase.auth.getUser(authHeader.replace('Bearer ', ''))
if (!authError) user = authUser
} else {
const { data: { user: sessionUser }, error: sessionError } = await supabase.auth.getUser()
if (!sessionError) user = sessionUser
}
} catch (e) {
// Ignore auth errors
}
if (!user) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
}
// Verify user has access to this book
const { data: book } = await supabase
.from('books')
.select('id, title')
.eq('id', bookId)
.eq('user_id', user.id)
.single()
if (!book) {
return NextResponse.json({ error: 'Book not found' }, { status: 404 })
}
// Start indexing process (async)
console.log(`๐ Starting semantic indexing for book: ${book.title}`)
// Don't await this - let it run in background
semanticIndexingService.processBook(bookId)
.then(() => {
console.log(`โ
Completed semantic indexing for book: ${book.title}`)
})
.catch((error) => {
console.error(`โ Failed to index book ${book.title}:`, error)
})
return NextResponse.json({
message: 'Indexing started',
bookId,
bookTitle: book.title
})
} catch (error) {
console.error('Start indexing error:', error)
return NextResponse.json(
{ error: 'Failed to start indexing' },
{ status: 500 }
)
}
}